package com.senter.demo.uhf;

import com.senter.support.openapi.StUhf;
import com.senter.support.openapi.StUhf.AccessPassword;
import com.senter.support.openapi.StUhf.Bank;
import com.senter.support.openapi.StUhf.InterrogatorModel;
import com.senter.support.openapi.StUhf.InterrogatorModelB;
import com.senter.support.openapi.StUhf.Result.ReadResult;
import com.senter.support.openapi.StUhf.Result.WriteResult;

public class Demo
{
	private static StUhf  stUhf;
	private static boolean isInited=false;
	
	public synchronized static boolean init()
	{
		if (isInited)
		{
			return true;
		}
		if (stUhf==null)
		{
			stUhf=StUhf.getUhfInstance();//这儿可能需要几秒的时间来检测模块
		}
		
		if (stUhf==null)
		{
			//模块没有获取到
			throw new IllegalStateException("模块没有获取到");
		}
		
		if (stUhf.getInterrogatorModel()!=InterrogatorModel.InterrogatorModelB)
		{
			//模块不对
			throw new IllegalStateException("适配的模块不对");
		}
		isInited=stUhf.init();
		return isInited;
	}
	
	public synchronized static void unint()
	{
		if (isInited)
		{
			stUhf.uninit();
			isInited=false;
		}
	}

	//KF 01 DM 01 01 03
	/**
	 * 数据是12个字节的ASCII码，正好占用6个整字的长度
	 */
	public synchronized static String readData()
	{
		if (isInited==false)
		{
			throw new IllegalStateException("请先初始化");
		}
		
		ReadResult rr=stUhf.getInterrogatorAs(InterrogatorModelB.class).readDataFromSingleTag(AccessPassword.getNewInstance(new byte[4]), Bank.User, 0, 6);
		if (rr==null)
		{
			return null;
		}
		if (rr.isSucceeded()==false)
		{
			return null;
		}
		byte[] data=rr.getData();
		if (data==null||data.length!=12)
		{
			return null;
		}
		return new String(data);
	}
	public synchronized static boolean writeData(String data)
	{
		if (isInited==false)
		{
			throw new IllegalStateException("请先初始化");
		}
		
		byte[] bytes=data.getBytes();
		if (bytes.length!=12)
		{
			throw new IllegalArgumentException("数据长度不对");
		}
		WriteResult rr=stUhf.getInterrogatorAs(InterrogatorModelB.class).writeBlockDataToSingleTag(AccessPassword.getNewInstance(new byte[4]), Bank.User, 0, bytes);
		if (rr==null)
		{
			return false;
		}
		if (rr.isSucceeded()==false)
		{
			return false;
		}
		if (rr.getWrittenWordsNum()!=6)
		{
			return false;
		}
		return true;
	}
	public synchronized static boolean setPower(int power)
	{
		if (isInited==false)
		{
			throw new IllegalStateException("请先初始化");
		}
		if (power<3||power>32)
		{
			throw new IllegalArgumentException();
		}
		return stUhf.getInterrogatorAs(InterrogatorModelB.class).setPower(power);
	}
}


